package chatBot.service.impl;

import chatBot.entity.Conversation;
import chatBot.entity.Message;
import chatBot.exception.IllegalOperationException;
import chatBot.mapper.ConversationMapper;
import chatBot.mapper.MessageMapper;
import chatBot.service.ConversationService;
import chatBot.utils.ContextHolderUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements ConversationService {

    @Resource
    private ConversationMapper conversationMapper;

    @Resource
    private MessageMapper messageMapper;

    @Override
    public List<Conversation> listConversations(Long userId) {
        if (userId == null) {
            throw new IllegalOperationException("用户ID不能为空");
        }

        // 查询当前用户的所有会话记录
        LambdaQueryWrapper<Conversation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Conversation::getUserId, userId) // 根据用户ID过滤
                .orderByDesc(Conversation::getCreateTime); // 按创建时间倒序排序

        return conversationMapper.selectList(queryWrapper); // 返回会话列表
    }


    @Override
    public Long createConversation(Conversation conversation) {
        if (conversation == null) {
            throw new IllegalOperationException("会话对象不能为空");
        }

        Long userId = ContextHolderUtil.getUserId();
        if (userId == null) {
            throw new IllegalOperationException("用户未登录，无法创建会话");
        }

        conversation.setUserId(userId); // 设置用户ID
        conversation.setCreateTime(LocalDateTime.now()); // 设置创建时间
        save(conversation); // 保存会话

        return conversation.getConversationId(); // 返回会话ID
    }

    @Override
    public void removeConversation(Long conversationId) {
        if (conversationId == null) {
            throw new IllegalOperationException("会话ID不能为空");
        }

        Long userId = ContextHolderUtil.getUserId();
        Conversation conversation = getById(conversationId);

        if (userId == null || conversation == null || !userId.equals(conversation.getUserId())) {
            throw new IllegalOperationException("无法删除其他用户的会话或用户未登录，或会话不存在");
        }

        // 删除相关消息记录
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getConversationId, conversationId);
        messageMapper.delete(queryWrapper);

        // 删除会话
        removeById(conversationId);
    }

    @Override
    public List<Message> messagesOfConversation(Long conversationId, Integer showItem) {
        if (conversationId == null) {
            throw new IllegalOperationException("会话ID不能为空");
        }

        Long userId = ContextHolderUtil.getUserId();
        Conversation conversation = conversationMapper.selectById(conversationId);

        // 校验会话是否属于当前登录用户
        if (userId == null || conversation == null || !userId.equals(conversation.getUserId())) {
            throw new IllegalOperationException("无法查询其他用户的会话或用户未登录，或会话不存在");
        }

        // 查询指定条数的会话消息
        return messageMapper.selectList(new LambdaQueryWrapper<Message>()
                .eq(Message::getConversationId, conversationId)  // 筛选会话ID
                .orderByAsc(Message::getMessageId)              // 按消息ID升序排序
                .last(showItem != null, "limit " + showItem));  // 限制返回条数
    }

    @Override
    public Conversation renameConversation(Long conversationId, String newName) {
        if (conversationId == null) {
            throw new IllegalOperationException("会话ID不能为空");
        }

        if (newName == null || newName.trim().isEmpty()) {
            throw new IllegalOperationException("新会话名称不能为空");
        }

        Long userId = ContextHolderUtil.getUserId();
        Conversation conversation = conversationMapper.selectById(conversationId);

        // 校验会话是否属于当前登录用户
        if (userId == null || conversation == null || !userId.equals(conversation.getUserId())) {
            throw new IllegalOperationException("无法重命名其他用户的会话或用户未登录，或会话不存在");
        }

        // 更新会话名称
        conversation.setConversationName(newName);
        conversationMapper.updateById(conversation);

        return conversation;
    }

}
